﻿using System;
using System.Web.Security.AntiXss;
using InhollandAir.auxiliary;

namespace InhollandAir
{
    public partial class Register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                foreach (var li in Sql.GetAllCountriesInWorld()) //Load all possible countries
                    ddlCountries.Items.Add(li);
        }
        protected void BtnCompleteRegistrationClick(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                lblRegistrationOutput.Text = AntiXssEncoder.HtmlEncode("Please correct the invalid values", false);
                return;
            }
            string un = AntiXssEncoder.HtmlEncode(txtUsername.Text.Trim(), false);
            if (string.Equals(Sql.CheckIfUserExists(un), "0"))
            {
                string pid = Sql.CreateNewPerson(int.Parse(Sql.CreateNewUser(un, txtPassword.Text.Trim())), un,
                                                 AntiXssEncoder.HtmlEncode(txtFirstName.Text.Trim(), false),
                                                 AntiXssEncoder.HtmlEncode(txtFamilyName.Text.Trim(), false),
                                                 AntiXssEncoder.HtmlEncode(txtBirthday.Text.Trim(), false),
                                                 ddlSex.SelectedValue,
                                                 AntiXssEncoder.HtmlEncode(txtPhoneNumber.Text.Trim(), false),
                                                 AntiXssEncoder.HtmlEncode(txtEmailAddress.Text.Trim(), false),
                                                 ddlCountries.SelectedValue,
                                                 AntiXssEncoder.HtmlEncode(txtPostalCode.Text.Trim(), false),
                                                 AntiXssEncoder.HtmlEncode(txtHouseNumber.Text.Trim(), false));

                int pidInt;
                if (int.TryParse(pid, out pidInt))
                {
                    Logging.LogEvent(pidInt, Request.Url, "Account creation: succesfull", string.Empty, false);
                    Response.Redirect("Login.aspx?msg=1");
                }
                else
                    lblRegistrationOutput.Text = AntiXssEncoder.HtmlEncode("We encoutered a database problem, please try again later.", false);
            }
            else
            {
                Logging.LogEvent(0, Request.Url, "Account creation: username in use", "Please choose a different username", false);
                lblRegistrationOutput.Text = AntiXssEncoder.HtmlEncode("Please choose a different username", false);
            }
        }
    }
}